Ext.ns("sh.extjs.module");
sh.extjs.module.LoginButton = Ext.extend(Ext.Button, {
    loginUrl: "",
    logoutUrl: "",
    hidden: false,
    initComponent: function(){
        sh.extjs.module.LoginButton.superclass.initComponent.call(this);
        this.on("click", function(){
            if(this.text == "Login"){
                this.getEditWin();
            }else if(this.text == "Logout"){
                this.reback();
            }
        }, this);
    },
    getEditWin: function(){
        if(!this.win){
            var formPanel = new Ext.form.FormPanel({
                labelAlign: "right",
                labelWidth: 80,
                border: false,
                layout: "form",
                method: "post",
                items: [
                    {height: 15, border: false},
                    {xtype: "textfield", fieldLabel: "username", name: "username"},
                    {xtype: "textfield", fieldLabel: "password", inputType:"password", name: "password"}
                ],
                buttonAlign: "center",
                buttons:[
                    {text: "Login", scope: this, handler: this.submitForm},
                    {text: "Close", scope: this, handler: function(){
                        this.win.hide();
                    }}
                ]
            });
            this.win = new Ext.Window({
                width: 300,
                height: 200,
                closeAction: 'hide',
                modal: true,
                layout: 'fit',
                items: [formPanel]
            });
        }
        this.cleanForm();
        this.win.show();
    },
    cleanForm : function() {
        this.win.getComponent(0).getForm().reset();
    },
    submitForm : function() {
        this.win.getComponent(0).getForm().submit({
            url: this.loginUrl,
            scope: this,
            waitMsg: "Please wait...",
            success: function(form, action){
                Ext.Msg.alert("Tip", "Success!");
                this.win.hide();
                this.toRefresh();
            },
            failure: function(form, acition){
                Ext.Msg.alert("Tip", "Failed!");
                this.win.hide();
            }
        });
    },
    reback: function(){
        var wartMsg = Ext.Msg.wait("", "Please Wait...");
        Ext.Ajax.request({
            url: this.logoutUrl,
            method : "post",
            async : false,
            scope : this,
            success : function(resp, opts) {
                wartMsg.hide();
//                Ext.Msg.alert("Tip", "Success!");
                this.toRefresh();
            },
            failure : function(resp, opts) {
                wartMsg.hide();
//                Ext.Msg.alert("Tip", "Failed!");
            }
        });
    },
    toRefresh: function(){
        window.location.reload();
    }
});